<template>
  <div>
    <hr />
    <el-row :gutter="20">
      <el-col :span="10">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="学生姓名">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="学生年龄">
            <el-input v-model="form.age"></el-input>
          </el-form-item>
          <el-form-item label="学生性别">
            <el-radio-group v-model="form.gender">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="学生专业">
            <el-select v-model="form.subjectsId" placeholder="请选择">
              <el-option
                v-for="item in subjects"
                :key="item._id"
                :label="item.name"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生班级">
            <el-select v-model="form.classesId" placeholder="请选择">
              <el-option
                v-for="item in classes"
                :key="item._id"
                :label="item.name"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateStudents"
              >确认修改</el-button
            >
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-upload
          class="avatar-uploader"
          action="http://47.98.128.191:3000/images/uploadImages"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.imagePath" :src="form.imagePath" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import {mapState,mapActions} from "vuex";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapActions } = createNamespacedHelpers("subjectsModule");
export default {
  props: ["id"],
  data() {
    return {
      form: {
        name: "",
        age: "",
        gender: "",
        subjectsId: "",
        classesId: "",
        imagePath: "",
      },

      // subjects: [],
      classes: [],
      isUpdate: false,
    };
  },
  //生命周期一进来就获取动态路由参数
  async created() {
    //第一种方式￥route
    console.log("$route", this.$route.params);
    //第二种方式props,需要现在路由配置中中添加props属性,然后再data上添加props:["动态路由名"]
    console.log("props", this.id);
    await this.getStudentById();
    this.getSubjects();
  },
  watch: {
    "form.subjectsId"(newValue, oldValue) {
      if (oldValue) {
        this.form.classesId = "";
      }

      console.log(this.form.subjectsId);
      this.getClassesBySid();
    },
  },
  computed: {
    ...mapState(["subjects"]),
  },
  methods: {
    ...mapActions(["getSubjectsAsync"]),
    async getStudentById() {
      const res = await this.$api.students.getById({
        _id: this.$route.params.id,
      }); //传的参数里面一低昂是一个对象
      if (res.code) {
        console.log(res.data);
        this.form = res.data;
      }
      console.log(res);
    },
    async getSubjects() {
      //复制函数使用方法
      this.getSubjectsAsync();

      //正常请求使用方法
      // const res = await this.$api.subjects.get();
      // console.log(res);

      // if (res.code) {
      //   this.subjects = res.data.rows;
      // }
    },
    async getClassesBySid() {
      const res = await this.$api.classes.getBySid({
        subjectsId: this.form.subjectsId,
      });
      console.log(res);
      if (res.code) {
        this.classes = res.data.rows;
      }
    },
    async updateStudents() {
      const res = await this.$api.students.update(this.form);
      if (res.code) {
        this.$message({
          message: "修改学生成功",
          type: "success",
        });
        this.isUpdate = true;
        this.$router.push("/home/studentList");
      } else {
        this.$message.error("修改学生失败");
      }
    },
    //图片新增
    handleAvatarSuccess(res, file) {
      this.form.imagePath = res.data[0];
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    //图片上传
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  beforeRouteLeave(to, from, next) {
    if (to.path.includes("/login")) {
      next();
      return;
    }
    if (!this.isUpdate) {
      // 进入 if，说明当前的数据还未提交
      this.$confirm("你还有数据未提交，确认离开吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          next();
        })
        .catch(() => {});
    } else {
      // 进入 else，说明当前的数据已经提交
      next();
    }
  },
};
</script>

<style scoped>
.el-input {
  width: 280px;
}
.el-select {
  width: 280px;
}
hr {
  margin-bottom: 30px;
}
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader >>> .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
